/**
 * 测试BasicItemService的getItemsByIds方法
 */

const mysql = require('mysql2/promise');

// 数据库连接配置
const DB_CONFIG = {
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    charset: 'utf8mb4'
};

class BasicItemServiceTester {
    constructor() {
        this.connection = null;
    }

    // 连接数据库
    async connectDatabase() {
        try {
            console.log('🔌 正在连接数据库...');
            this.connection = await mysql.createConnection(DB_CONFIG);
            console.log('✅ 数据库连接成功');
        } catch (error) {
            console.error('❌ 数据库连接失败:', error.message);
            throw error;
        }
    }

    // 关闭数据库连接
    async closeDatabase() {
        if (this.connection) {
            await this.connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }

    // 模拟BasicItemService的getItemsByIds方法
    async getItemsByIds(ids) {
        if (!ids || ids.length === 0) {
            return [];
        }

        const placeholders = ids.map(() => '?').join(',');
        const sql = `
            SELECT 
                id,
                name,
                gold_price as goldPrice,
                silver_price as silverPrice,
                lv,
                weight,
                description,
                pic,
                is_treasure_shop as isTreasureShop,
                is_exp_shop as isExpShop,
                status
            FROM basic_items 
            WHERE id IN (${placeholders}) AND status = 1
            ORDER BY id ASC
        `;

        const [rows] = await this.connection.execute(sql, ids);
        return rows;
    }

    // 测试杂物类物品 (t=3)
    async testMiscItems() {
        console.log('\n🧪 测试杂物类物品 (t=3)...');

        const itemIds = [71, 72, 74, 75, 108, 109];
        const items = await this.getItemsByIds(itemIds);

        console.log(`✅ 查询到 ${items.length} 个杂物类物品:`);
        items.forEach(item => {
            console.log(`   ID: ${item.id}, 名称: ${item.name}, 银币价格: ${item.silverPrice}, 图片: ${item.pic || 'none.png'}`);
        });

        return items;
    }

    // 测试矿物类物品 (t=2)
    async testMineralItems() {
        console.log('\n🧪 测试矿物类物品 (t=2)...');

        const itemIds = [58, 38, 48, 39, 49, 59, 60, 50, 40, 61, 41, 51, 62, 42, 52, 63, 53, 43, 54, 44, 64, 55, 45, 65, 56, 46, 66, 57, 47, 67];
        const items = await this.getItemsByIds(itemIds);

        console.log(`✅ 查询到 ${items.length} 个矿物类物品:`);
        items.forEach(item => {
            console.log(`   ID: ${item.id}, 名称: ${item.name}, 银币价格: ${item.silverPrice}, 图片: ${item.pic || 'none.png'}`);
        });

        return items;
    }

    // 测试WebSocket指令1265的响应格式
    async testWS1265Response() {
        console.log('\n🧪 测试WebSocket指令1265响应格式...');

        // 测试杂物类 (t=3)
        const miscItems = await this.testMiscItems();
        const miscResponse = {
            act_id: 1265,
            code: 0,
            list: miscItems.map(item => ({
                id: item.id,
                name: item.name,
                pic: item.pic || 'none.png',
                price: item.silverPrice
            }))
        };

        console.log('\n📤 杂物类响应格式:');
        console.log(JSON.stringify(miscResponse, null, 2));

        // 测试矿物类 (t=2)
        const mineralItems = await this.testMineralItems();
        const mineralResponse = {
            act_id: 1265,
            code: 0,
            list: mineralItems.map(item => ({
                id: item.id,
                name: item.name,
                pic: item.pic || 'none.png',
                price: item.silverPrice
            }))
        };

        console.log('\n📤 矿物类响应格式:');
        console.log(JSON.stringify(mineralResponse, null, 2));

        return { miscResponse, mineralResponse };
    }

    // 验证数据完整性
    async validateDataIntegrity() {
        console.log('\n🔍 验证数据完整性...');

        const miscIds = [71, 72, 74, 75, 108, 109];
        const mineralIds = [58, 38, 48, 39, 49, 59, 60, 50, 40, 61, 41, 51, 62, 42, 52, 63, 53, 43, 54, 44, 64, 55, 45, 65, 56, 46, 66, 57, 47, 67];

        const miscItems = await this.getItemsByIds(miscIds);
        const mineralItems = await this.getItemsByIds(mineralIds);

        console.log(`📊 杂物类: 期望 ${miscIds.length} 个，实际 ${miscItems.length} 个`);
        console.log(`📊 矿物类: 期望 ${mineralIds.length} 个，实际 ${mineralItems.length} 个`);

        // 检查缺失的物品
        const foundMiscIds = miscItems.map(item => item.id);
        const foundMineralIds = mineralItems.map(item => item.id);

        const missingMisc = miscIds.filter(id => !foundMiscIds.includes(id));
        const missingMineral = mineralIds.filter(id => !foundMineralIds.includes(id));

        if (missingMisc.length > 0) {
            console.log(`⚠️ 杂物类缺失物品ID: ${missingMisc.join(', ')}`);
        }

        if (missingMineral.length > 0) {
            console.log(`⚠️ 矿物类缺失物品ID: ${missingMineral.join(', ')}`);
        }

        if (missingMisc.length === 0 && missingMineral.length === 0) {
            console.log('✅ 数据完整性验证通过');
        }

        return {
            miscItems,
            mineralItems,
            missingMisc,
            missingMineral
        };
    }

    // 运行所有测试
    async runAllTests() {
        console.log('🚀 开始BasicItemService测试...\n');

        try {
            // 1. 连接数据库
            await this.connectDatabase();

            // 2. 测试杂物类物品
            await this.testMiscItems();

            // 3. 测试矿物类物品
            await this.testMineralItems();

            // 4. 测试WebSocket响应格式
            await this.testWS1265Response();

            // 5. 验证数据完整性
            await this.validateDataIntegrity();

            console.log('\n🎉 所有测试完成！');

        } catch (error) {
            console.error('💥 测试过程中发生错误:', error.message);
        } finally {
            // 6. 关闭数据库连接
            await this.closeDatabase();
        }
    }
}

// 运行测试
async function main() {
    console.log('🎯 BasicItemService测试工具');
    console.log('   目标：验证getItemsByIds方法和WebSocket指令1265响应格式\n');

    const tester = new BasicItemServiceTester();
    await tester.runAllTests();
}

// 如果直接运行此脚本
if (require.main === module) {
    main().catch((error) => {
        console.error('💥 脚本执行失败:', error.message);
        process.exit(1);
    });
}

module.exports = BasicItemServiceTester;
